package com.zz.yt.lib.ui.view.phone;

import android.content.Context;
import android.content.res.TypedArray;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.blankj.utilcode.util.ObjectUtils;
import com.blankj.utilcode.util.RegexUtils;
import com.blankj.utilcode.util.ThreadUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.whf.android.jar.dao.UserDao;
import com.zz.yt.lib.ui.R;
import com.zz.yt.lib.ui.listener.OnClickBoolListener;
import com.zz.yt.lib.ui.listener.OnClickStringListener;
import com.zz.yt.lib.ui.view.base.BaseLinearLayout;

import java.util.concurrent.TimeUnit;

/**
 * 手机号及验证自定义控件
 *
 * @author qf
 * @version 1.0
 */
public class PhoneCodeView extends BaseLinearLayout implements TextWatcher {

    private final TextView idTextCode;
    private int suspendInit = 60;
    private int suspend = 1;
    /*** 是否可以计时 */
    private boolean isTiming = true;
    private OnClickStringListener mClickStringListener = null;
    private OnClickBoolListener mClickBoolListener = null;

    protected int setLayout() {
        return R.layout.hai_view_phone_code;
    }

    public PhoneCodeView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        TypedArray attributes = context.obtainStyledAttributes(attrs, R.styleable.PhoneCodeView);
        if (attributes != null) {

            boolean editable = attributes.getBoolean(R.styleable.PhoneCodeView_android_enabled, true);
            setXianShow(editable);

            int max = attributes.getInt(R.styleable.PhoneCodeView_android_max, 60);
            setSuspend(max);

            //回收属性
            attributes.recycle();
        }
        idTextCode = findViewById(R.id.login_text_code);
        idTextCode.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                String phone = getTextStr(R.id.login_edit_phone);
                if (isPhone(phone) && isTiming) {
                    startTiming();
                    if (mClickStringListener != null) {
                        mClickStringListener.onClick(phone);
                    }
                }
            }
        });
        setOnClickListener(R.id.login_edit_phone);
        addTextChangedListener(R.id.login_edit_code, this);
        setOnFocusChangeListener(R.id.login_edit_phone, new OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    findViewById(R.id.login_view_phone).setBackgroundResource(R.color.colorAccent);
                } else {
                    findViewById(R.id.login_view_phone).setBackgroundResource(R.color.dim_grey);
                }
            }
        });
        setOnFocusChangeListener(R.id.login_edit_code, new OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    findViewById(R.id.login_view_code).setBackgroundResource(R.color.colorAccent);
                } else {
                    findViewById(R.id.login_view_code).setBackgroundResource(R.color.dim_grey);
                }
            }
        });
        setPhone(UserDao.getUserPhone());
    }

    public void setXianShow(boolean show) {
        setShow(R.id.login_view_phone, show);
        setShow(R.id.login_view_code, show);
    }

    /**
     * @param suspend:设置最大的计时长度（单位秒）
     */
    public void setSuspend(int suspend) {
        this.suspendInit = suspend;
    }

    /**
     * 停止计时
     */
    public void endTiming() {
        idTextCode.setText("获取验证码");
        idTextCode.setEnabled(true);
        isTiming = true;
    }

    /**
     * @param id:输入监控
     */
    private void setOnClickListener(int id) {
        final EditText editText = findViewById(id);
        if (editText != null) {
            editText.addTextChangedListener(new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                }

                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {

                }

                @Override
                public void afterTextChanged(Editable s) {
                    if (idTextCode != null) {
                        idTextCode.setEnabled(getPhone().length() > 10);
                    }
                }
            });
        }
    }

    public void setOnClickStringListener(OnClickStringListener listener) {
        this.mClickStringListener = listener;
    }

    public void setOnClickBoolListener(OnClickBoolListener listener) {
        this.mClickBoolListener = listener;
    }

    /**
     * @param phone:设置手机号
     */
    public void setPhone(String phone) {
        setText(R.id.login_edit_phone, phone);
        if (ObjectUtils.isNotEmpty(phone)) {
            endTiming();
        }
    }

    /**
     * @param timing:是否可以计时
     */
    public void setTiming(boolean timing) {
        isTiming = timing;
    }

    /**
     * 计时
     */
    private void startTiming() {
        isTiming = false;
        suspend = suspendInit;
        ThreadUtils.executeByFixedAtFixRate(1, new ThreadUtils.SimpleTask<String>() {

            @Override
            public String doInBackground() {
                return (suspend > 0 && !isTiming) ? suspend + " 秒" : "获取验证码";
            }

            @Override
            public void onSuccess(@Nullable String result) {
                suspend--;
                if (suspend < 0 || isTiming) {
                    isTiming = true;
                    cancel();
                }
                if (idTextCode != null) {
                    idTextCode.setText(result);
                    idTextCode.setEnabled(isTiming);
                }
            }
        }, 1, TimeUnit.SECONDS);
    }

    public String getPhone() {
        return getTextStr(R.id.login_edit_phone);
    }

    public String getPhoneCode() {
        return getTextStr(R.id.login_edit_code);
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override
    public void afterTextChanged(Editable s) {
        if (mClickBoolListener != null) {
            mClickBoolListener.onClick(getPhoneCode().length() > 1);
        }
    }

    /**
     * 判断手机号码
     *
     * @param phone：手机号码
     * @return true
     */
    public boolean isPhone(String phone) {
        if (TextUtils.isEmpty(phone)) {
            ToastUtils.showShort("请输入手机号码");
            return false;
        }
        if (phone.length() != 11 || !RegexUtils.isMobileExact(phone)) {
            ToastUtils.showShort("请输入正确的手机号码");
            return false;
        }
        return true;
    }

}
